/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.wdm.parsers;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.wdm.beans.points.Point;

/**
 *
 * @author thanasis
 */
public class GeocodingParser {
    public static Point parse(String location){
        double latitude = 0.0;
        double longitude = 0.0;
        Pattern p = Pattern.compile("[0-9]+\\.[0-9]+,\\-?[0-9]+\\.[0-9]+");
        Matcher m = p.matcher(location);
        boolean coords = m.matches();
        if(!coords){
        StringBuilder sb = new StringBuilder("http://maps.googleapis.com/maps/api/geocode/json?");
        sb.append("address=").append(location.replaceAll(" ", "%20")).append("&");
        sb.append("sensor=").append("false");
        
        //Sending a request to google directions service
        StringBuilder json = new StringBuilder();
        try {
            //Encoding the request url
            URL url = new URL(sb.toString().replaceAll(" ", "%20"));

            //Reading the result of the request
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = "";
            while ((line = in.readLine()) != null) {
                json.append(line);
            }
            in.close();
        } catch (IOException e) {
        }
        
        //Deserializing json into java objects using parser
        JsonParser parser = new JsonParser();

        //Getting the root element
        JsonObject root = parser.parse(json.toString()).getAsJsonObject();
        
        JsonArray resultsArray = root.getAsJsonArray("results");
        JsonElement firstResult = resultsArray.get(0);
        JsonElement geometry = firstResult.getAsJsonObject().get("geometry");
        JsonElement locationObject = geometry.getAsJsonObject().get("location");
        latitude = locationObject.getAsJsonObject().get("lat").getAsDouble();
        longitude = locationObject.getAsJsonObject().get("lng").getAsDouble();
        } else {
            latitude = Double.parseDouble(location.split(",")[0]);
            longitude = Double.parseDouble(location.split(",")[1]);
        }
        return new Point(latitude, longitude);
    }
}
